package com.jdzy.student.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdzy.common.constants.CommonConstants;
import com.jdzy.common.constants.StudentConstants;
import com.jdzy.common.exception.JdzuException;
import com.jdzy.model.common.vos.Result;
import com.jdzy.model.common.vos.ResultCodeEnum;
import com.jdzy.model.student.pojos.EventAnnouncements;
import com.jdzy.model.teacher.dtos.LoginDto;

import com.jdzy.model.teacher.dtos.SysUserDto;
import com.jdzy.model.teacher.pojos.SysUser;
import com.jdzy.model.teacher.vos.LoginVo;
import com.jdzy.student.mapper.SysUserMapper;
import com.jdzy.student.properties.JwtProperties;
import com.jdzy.student.service.SysUserService;
import com.jdzy.utils.common.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class  SysUserServiceImpl  extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public LoginVo login(LoginDto loginDto) {

        // 根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        if(sysUser == null) {
            throw new JdzuException(ResultCodeEnum.SUCCESS) ;
        }

        // 验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(sysUser.getPassword())) {
            throw new JdzuException(ResultCodeEnum.LOGIN_ERROR) ;
        }


        //4、开始生成jwt令牌
        Map<String,Object> claims=new HashMap<>();
        claims.put("userName",sysUser.getUserName());
        String jwt = JwtUtils.createJWT(jwtProperties.getStudentSecretKey(), jwtProperties.getStudentTtl(), claims);
        Map<String,String> res=new HashMap<>();
        res.put(StudentConstants.TOKEN_NAME,jwt);
        String token = jwt;
//        return ResultA.success(jwt);

        // 构建响应结果对象
        LoginVo loginVo = new LoginVo() ;
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        // 返回
        return loginVo;
    }

    @Override
    public Result getTeacherInfo(String token) {
        //1、解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(jwtProperties.getStudentSecretKey(), token);
            String userName = (String) claims.get("userName");
            //获取用户信息
            Result result = getSysUserById(userName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(CommonConstants.PARAM_ERROR);
        }
    }

    /**
     * 根据用户名查询用户信息
     * @param userName
     * @return
     */
    @Override
    public Result getSysUserById(String userName) {

        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, userName);
        SysUser user = sysUserMapper.selectOne(sysUserLambdaQueryWrapper);
        if (user != null) {
            return Result.success(user, "查询成功");
        } else {
            return Result.error("用户不存在");
        }
    }



    @Override
    public void saveSysUser(SysUser sysUser) {
        // 根据输入的用户名查询用户
        SysUser dbSysUser = sysUserMapper.findByUserName(sysUser.getUserName()) ;
        if(dbSysUser != null) {
            throw new JdzuException(ResultCodeEnum.USER_NAME_IS_EXISTS) ;
        }

        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);
        sysUserMapper.saveSysUser(sysUser) ;
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser) ;
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId) ;
    }

    @Override
    public IPage<SysUser> findByPage(long current, long size) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        // 可以在这里添加任何需要的查询条件
        return  sysUserMapper.selectPage(new Page<>(current, size), queryWrapper);
    }



}
